angular.module('starter.controllers')
.controller('TicketdetailCtrl', function($scope, museumFac, $stateParams, $location, $ionicScrollDelegate, cfg, $state, $cookies, uploadImg, $timeout) {
  $scope.order = {};
  $scope.order.num = 1;
  $scope.pay_order = {};

  $scope.exhibitionId = $stateParams.id;

  $scope.backhome = function(){
    $location.url('home');
  }

  $scope.gotoCenter = function(){
    museumFac.user.usertest(function(data){
      if(data.info == true){
        $location.url('center');
      }else{
        $scope.url = window.location.href;
            $cookies.put('lastPage', $scope.url);
        $location.url('login');
      }
    });
  }

  $scope.change_language = function(id){
      $scope.language = id;
      var expireDate = new Date();  
    expireDate.setDate(expireDate.getDate() + 30);                
    $cookies.put('language', id, {'expires': expireDate.toUTCString()});
    location.reload();
    if(id == 0){
      document.getElementById('title').innerHTML = '提示';
      document.getElementById('windowclosebutton').value = '确定';
    }else{
      document.getElementById('title').innerHTML = 'Hint';
      document.getElementById('windowclosebutton').value = 'Confirm';
    }

  }

  $scope.getLanguage = function(){
    $scope.language = $cookies.get('language');
    if($scope.language){
        $scope.language = $scope.language;

        if($scope.language == 0){
          document.getElementById('title').innerHTML = '提示';
          document.getElementById('windowclosebutton').value = '确定';
        }else{
          document.getElementById('title').innerHTML = 'Hint';
          document.getElementById('windowclosebutton').value = 'Confirm';
        }

    }else{
        $scope.language = 0;

        if($scope.language == 0){
          document.getElementById('title').innerHTML = '提示';
          document.getElementById('windowclosebutton').value = '确定';
        }else{
          document.getElementById('title').innerHTML = 'Hint';
          document.getElementById('windowclosebutton').value = 'Confirm';
        }
    }
  }
  $scope.getLanguage();


  $scope.add = function(){
    if($scope.order.num < $scope.buylimit){
      $scope.order.num ++;
    }
  }

  $scope.delete = function(){
  	if($scope.order.num > 1){
  	  $scope.order.num --;
      if($scope.order.num <= $scope.buylimit){
        $scope.morethan = 0;
      }
  	}
  }

  $scope.check_morethan = function(){
    if($scope.order.num - $scope.buylimit > 0){
      $scope.morethan = 1;
    }else{
      $scope.morethan = 0;
    }
  }

  $scope.checkOpenid = function(){
    museumFac.user.usertest(function(data){
        $scope.is_login = data.info;
      },function(data){
        alert(data.data.info);
    });
  }
  // $scope.checkOpenid();

  $scope.choose_ticket = function(key,list){
  	angular.forEach($scope.tickets, function(item){
  	  item.is_chosen = 0;
  	});
  	list.is_chosen = 1;
    $scope.ticket = list;
    if($scope.detail.limit&&$scope.detail.limit!=0){
      $scope.buylimit = $scope.detail.limit - $scope.detail.paid;
    }else{
      $scope.buylimit = $scope.ticket.stock;
    }   
    $scope.order.num = 1;
    $scope.morethan = 0;
  }

  $scope.show = 0;
  $scope.showDetail = function(){
  	$scope.show = !$scope.show;

    $ionicScrollDelegate.$getByHandle('mainScroll').resize();

    if($scope.show == 1){
      var par = document.getElementById("textdetail");
      $scope.top = angular.element(par).prop('offsetTop');
      $ionicScrollDelegate.scrollTo(0,$scope.top+25);
    }else{
      $ionicScrollDelegate.scrollTo(0,$scope.top);
      $ionicScrollDelegate.$getByHandle('mainScroll').resize();
    }
     
  }

  $scope.getDetail = function(){
    museumFac.info.exhibitiondetail({
      exhibitionId:$stateParams.id
    },function(data){
        $scope.detail = data.info;
        $scope.tickets = data.info.tickets;
        $scope.tickets[0].is_chosen = 1;
        $scope.ticket = $scope.tickets[0];
        if($scope.detail.limit&&$scope.detail.limit!=0){
          $scope.buylimit = $scope.detail.limit - $scope.detail.paid;
        }else{
          $scope.buylimit = $scope.ticket.stock;
        }
        $scope.url = cfg.baseUrl + 'home/index/gotoTicketDetail?id=' + $stateParams.id;

        $timeout(function() {
          if($scope.detail.begin_date == $scope.detail.end_date){
            $scope.starttime = $('.starttime').text();
            $scope.sharetime = '四方当代美术馆\r\n'+ $scope.starttime;
          }else{
            $scope.starttime = $('.starttime').text();
            $scope.endtime = $('.endtime').text();
            $scope.sharetime = '四方当代美术馆\r\n'+ $scope.starttime + ' - ' + $scope.endtime;
          }
          
          wx.ready(function(){
            wx.onMenuShareTimeline({
              title: $scope.detail.name + '| 在线购票\r\n' + $scope.sharetime, // 分享标题
              // desc: $scope.sharetime, // 分享描述
              link: $scope.url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
              imgUrl: cfg.baseImgUrl+$scope.detail.banner_path, // 分享图标
              success: function () { 
                  // 用户确认分享后执行的回调函数
              },
              cancel: function () { 
                  // 用户取消分享后执行的回调函数
              }
          });
          // 获取“分享给朋友”按钮点击状态及自定义分享内容接口
          wx.onMenuShareAppMessage({
              title: $scope.detail.name+' | 在线购票',  // 分享标题
              desc: $scope.sharetime, // 分享描述
              link: $scope.url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
              imgUrl: cfg.baseImgUrl+$scope.detail.banner_path, // 分享图标
              type: '', // 分享类型,music、video或link，不填默认为link
              dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
              success: function () { 
                  // 用户确认分享后执行的回调函数
              },
              cancel: function () { 
                  // 用户取消分享后执行的回调函数
              }
            });
          });

        }, 100);
        

      },function(data){
        alert(data.data.info);
    });
  }
  $scope.getDetail();

  $scope.pay = function(){

    museumFac.wechat.confirmtorder($scope.pay_order, function(response) {
      var res = response;
      if (res.info) {
        document.getElementById('title').innerHTML = '提示';
        document.getElementById('windowclosebutton').value = '确定';
        $scope.successtext = res.info;
        alert($scope.successtext);
        $state.go('tab.my_ticket');
        return;
      }
      // console.log(res.redirect);
      var jsApiCall = function(data) {
        WeixinJSBridge.invoke(
          'getBrandWCPayRequest',
          data,
          function(res) {
            WeixinJSBridge.log(res.err_msg);
                  // alert(res.err_code+res.err_desc+res.err_msg);
              if (res.err_msg == 'get_brand_wcpay_request:ok') {
                  $scope.guide = 0;
                  if($scope.language == 0){
                    document.getElementById('title').innerHTML = '提示';
                    document.getElementById('windowclosebutton').value = '确定';
                    $scope.successtext = "购票成功！请至公众号菜单「我的门票」中查看兑换码。";
                  }else{
                    document.getElementById('title').innerHTML = 'Hint';
                    document.getElementById('windowclosebutton').value = 'Confirm';
                    $scope.successtext = "Purchase succeeded!Find the redeem codes through 「我的门票」 in Sifang Art Museum's WeChat Official Account menus.";
                  }
                  
                  alert($scope.successtext);
                  $state.go('tab.my_ticket');
                } else if (res.err_msg == 'get_brand_wcpay_request:cancel') {
                  $scope.guide = 0;
                  if($scope.language == 0){
                    alert("已取消支付!");
                  }else{
                    alert("Payment canceled");
                  }
                } else if (res.err_msg == 'get_brand_wcpay_request:fail') {
                  $scope.guide = 0;
                  if($scope.language == 0){
                    alert("支付失败!");
                  }else{
                    alert("Payment failed");
                  }
                } else {
                  $scope.guide = 0;
                  if($scope.language == 0){
                    alert('支付失败' + res.err_msg);
                  }else{
                    alert('Payment failed' + res.err_msg);
                  }
                };
              }
            );
      }
      jsApiCall(res);
    }, function(data) {
      alert(data.data.info);
    });
  }

  $scope.sureorder = function(){
    $scope.order_mark = 0;
    $scope.pay();
  }

  $scope.cancelorder = function(){
    $scope.order_mark = 0;
  }

  $scope.payOrder = function() {
    $scope.pay_order.ticket_id = $scope.ticket.id;
    $scope.pay_order.amount = $scope.order.num;
    museumFac.user.usertest(function(data){
        $scope.is_login = data.info;

        if($scope.is_login == true){
          if($scope.detail.type == '1'){
            $scope.guide = '1';
          }else{
            if($scope.ticket.price==0){
              // if(confirm('是否确认预约'+$scope.detail.name+$scope.ticket.name+'?')){
              //   $scope.pay();
              // }
              $scope.order_mark = 1;
            }else{
              $scope.pay();
            }
          }

          }else{
            $scope.url = cfg.baseUrl + 'home/index/exhibition?exhibitionId=' + $stateParams.id;
            $cookies.put('lastPage', $scope.url);
            $location.url('login');
          }

      },function(data){
        alert(data.data.info);
    }); 
  }

  $scope.cancel_mbwhite = function(){
    $scope.guide = 0;
  }

  $scope.panduan = function(){
    if($scope.detail.type == '1'){
      if(!$scope.detail.user.vip){
        $scope.vip_mark = 1;
      }else{
        $scope.payOrder();
      }
    }else{
      $scope.payOrder();
    }
  }

  $scope.sureorder1 = function(){
    $scope.vip_mark = 0;
  }

})